import React, { useEffect, useState } from 'react';
import './equ.scss'
import { set_EqiList, del_Emp, add_Emp, edit_Emp, del_EmpAllStu } from '../../../store/list/index'
import { EquGetList } from '../../../api/index'
import Navbar1 from '../../../components/navbar1/navbar1';
import { useAppDispatch, useAppSelector } from '../../../unit/Hooks';
import { Button, Segmented, Space, Select, Switch, Table, Typography } from 'antd';
import type { TableColumnsType } from 'antd';
import type { PopconfirmProps } from 'antd';
import { message, Popconfirm } from 'antd';
import { Modal } from 'antd';
import type { FormProps } from 'antd';
import { Checkbox, Form, Input } from 'antd';



interface DataType {
  key: React.Key;
  name: string;
  age: number;
  address: string;
}
function equipment() {
  //渲染数据
  const dispatch = useAppDispatch()
  useEffect(() => {
    (
      async () => {
        let res = await EquGetList()
        dispatch(set_EqiList(res.data.data.result[0].list))
        console.log(res.data.data.result[0].list);
      }
    )()
  }, [])
  const data = useAppSelector(state => {
    return state.list.data
  })
  console.log('设备运维', data);

  // 删除
  const confirm = (key: any) => {
    dispatch(del_Emp(key))
    message.success('确定删除');
  };
  // 批量删除
  const allDel = () => {
    dispatch(del_EmpAllStu(selectedRowKeys)); //批量删除派发
    selectedRowKeys.length = 0;
  }
  const cancel: PopconfirmProps['onCancel'] = (e) => {
    // console.log(e);
    message.error('Click on No');
  };
  //新增 编辑
  //Model对话框
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [title, setTitle] = useState('')
  const [key, setKey] = useState('')
  const [form] = Form.useForm();
  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  //增加 
  const add = () => {
    showModal()
    setTitle('新增')
    form.resetFields();
  }
  // 编辑
  const edit = (values: any) => {
    showModal()
    setTitle('编辑')
    setKey(values.key)
    form.setFieldsValue({
      stuName: values.stuName,
      address: values.address,
      switch: values.switch,
      stuNo: values.stuNo,
      className: values.className,
      salary: values.salary,
      workCity: values.workCity,
      expertiseName: values.expertiseName,
      origin: values.origin,
      collegeName: values.collegeName,
      gradYear: values.gradYear,
      createdTime: values.createdTime,
    });
  }
  // 增加 编辑共用表单
  type FieldType = {
    key: string;
    // createdTime?: string;
    stuName?: string;
    // address?: string;
    stuNo?: string;
    // className?: string;
    salary?: string;
    // workCity?: string;
    expertiseName?: string;
    origin?: string;
    // collegeName?: string;
    gradYear?: string;
    image?: string;
    switch?: boolean;
  };

  const onFinish = (values: FieldType) => {
    if (title === '新增') {
      values.key = new Date().toLocaleString()
      dispatch(add_Emp(values))
    } else {
      values.key = key
      dispatch(edit_Emp(values))
    }
    // console.log('Success:', values);
  };
  const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  //搜索
  const [filtedTable, setfiltedTable] = useState([])
  const goSearchs = (value: any) => {
    // console.log(value, '222');
    const filterData = data.filter((item: any) => {
      return (
        (value.stuName ? item.stuName.includes(value.stuName) : true) && (value.origin ? item.origin.includes(value.origin) : true) && (value.workCity && value.workCity.length ? value.workCity.some(city => item.workCity.includes(city)) : true)
      )
    })
    setfiltedTable(filterData)
    // console.log('搜索后数据', filterData);

  }
  useEffect(() => {
    setfiltedTable(data)
  }, [data])


  const columns: TableColumnsType<DataType> = [
    {
      title: 'ID',
      dataIndex: 'stuNo',
      key: 'stuNo',
    },
    {
      title: '设备维修人员',
      dataIndex: 'stuName',
      key: 'stuName',
    },
    {
      title: '实时检测图',
      dataIndex: 'image',
      key: 'image',
      render: (text: string) => <img style={{ width: '50px', height: '30px' }} src={text} alt="" />,
    },
    {
      title: '场地使用',
      dataIndex: 'bourn',
      key: 'bourn',
    },
    {
      title: '设备检测',
      dataIndex: 'switch',
      key: 'switch',
      render: (title) => {
        if (title == 1) {
          return <Switch checkedChildren='正常' unCheckedChildren={title} defaultChecked />
        } else {
          return <Switch checkedChildren='不正常' unCheckedChildren={title} />
        }
      }
    },
    {
      title: '实时用电',
      dataIndex: 'expertiseName',
      key: 'expertiseName',
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => edit(record)}>查看</a>
          <Popconfirm
            title="Delete the task"
            description="Are you sure to delete this task?"
            onConfirm={() => confirm(record.stuNo)}
            onCancel={() => cancel}
            okText="Yes"
            cancelText="No"
          >
            <Button type='primary'>删除</Button>
          </Popconfirm>
          <a onClick={() => edit(record)}>编辑</a>
        </Space>
      ),
    },
  ];
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  return (
    <div className='equBox'>
      <div className="top">
        <Navbar1 goSearch={goSearchs}></Navbar1>
      </div>
      <div className="foot">
        <div className="btnBox">
          <Button type="primary" onClick={add}>新增毕业学生</Button>
          {/* 新增 model对话框 */}
          <Modal title={title} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
            <Form
              form={form}
              name="basic"
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 16 }}
              style={{ maxWidth: 600 }}
              initialValues={{ remember: true }}
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
              autoComplete="off"
            >

              <Form.Item<FieldType>
                label="学生学号"
                name="stuNo"
                rules={[{ required: true, message: 'Please input your stuNo!' }]}
              >
                <Input />
              </Form.Item>

              <Form.Item<FieldType>
                label="学生姓名"
                name="stuName"
                rules={[{ required: true, message: 'Please input your stuName!' }]}
              >
                <Input />
              </Form.Item>

              <Form.Item<FieldType>
                label="检测实时图"
                name="image"
                rules={[{ required: true, message: 'Please input your className!' }]}
              >
                <Input />
              </Form.Item>

              <Form.Item<FieldType>
                label="检测区域"
                name="salary"
                rules={[{ required: true, message: 'Please input your salary!' }]}
              >
                <Input />
              </Form.Item>

              <Form.Item<FieldType>
                label="检测环境状态"
                name="switch"
                rules={[{ required: true, message: 'Please input your workCity!' }]}
              >
                <Input />
              </Form.Item>

              <Form.Item<FieldType>
                label="用水检测"
                name="expertiseName"
                rules={[{ required: true, message: 'Please input your expertiseName!' }]}
              >
                <Input />
              </Form.Item>
              <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                <Button type="primary" htmlType="submit">
                  确认
                </Button>
              </Form.Item>
            </Form>
          </Modal>
          <Button type="primary" onClick={allDel}>批量删除</Button>
          <Button type="primary">学生批量导入</Button>
          <Button type="primary">学生信息导出</Button>
        </div>
        <Table rowSelection={rowSelection} columns={columns} dataSource={data} rowKey={(record) => record.stuNo} />
      </div>

    </div>
  )
}

export default equipment
